package com.wowangz.cms.systemmanage.translator.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iol.common.http.HttpRequestFactory;
import com.iol.common.http.HttpRequestMethod;
import com.wowangz.cms.syscore.utils.PropertyPlaceholderConfigurerExt;
import com.wowangz.cms.systemmanage.translator.CoreServerContants;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorAbilityMapper;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorMapper;
import com.wowangz.cms.systemmanage.translator.dao.TranslatorTagsMapper;
import com.wowangz.cms.systemmanage.translator.pojo.CoreServerBaseParam;
import com.wowangz.cms.systemmanage.translator.pojo.SaveOrUpdateTranslatorParam;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslator;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslatorAbility;
import com.wowangz.cms.systemmanage.translator.pojo.TblTranslatorTags;

/**
 * 
 * 调用core server服务
 *
 * @author wosen.wang
 * @version 1.0
 * @since 2016年6月22日
 */
@Service("coreServerAPIService")
public class CoreServerAPIService {

	private static String CORESERVER_TOKEN = "CORESERVER_TOKEN_KEY_";

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private TranslatorMapper translatorMapper;

	@Autowired
	private TranslatorAbilityMapper translatorAbilityMapper;

	@Autowired
	private TranslatorTagsMapper translatorTagsMapper;

	@Autowired
	private PropertyPlaceholderConfigurerExt placeholderConfig;

	/**
	 * 请求core server服务token
	 * 
	 * @return
	 */
	public String getToken() {
		String tokenStr = "";
//		Object obj = stringRedisTemplate.opsForValue().get(CORESERVER_TOKEN);
//		if (obj == null) {
			String coreserverHostUrl = (String) PropertyPlaceholderConfigurerExt.getContextProperty("coreserver.root.url");
			String trserverBaseKey = (String) PropertyPlaceholderConfigurerExt.getContextProperty("trserver.base.key");
			String trserverBaseSecret = (String) PropertyPlaceholderConfigurerExt.getContextProperty("trserver.base.secret");
			String url = coreserverHostUrl + CoreServerContants.TOKEN_URL;
			CoreServerBaseParam req = new CoreServerBaseParam();
			req.setAppKey(trserverBaseKey);
			req.setAppSecret(trserverBaseSecret);
			String result = HttpRequestFactory.getHttpRequest(HttpRequestMethod.POST).send(url, req);
			JSONObject json = JSON.parseObject(result);
			if (null != json && json.containsKey("data")) {
				tokenStr = json.getString("data");
				stringRedisTemplate.opsForValue().set(CORESERVER_TOKEN, tokenStr, 6600, TimeUnit.SECONDS);
			} else {
				throw new RuntimeException("请求token失败");
			}
			// token存redis 设置失效时间 设置110分钟超时(小于2个小时)
//		} else {
//			tokenStr = (String) obj;
//		}

		return tokenStr;
	}

	/**
	 * 向coreserver注册或更新译员
	 * 
	 * @param translator
	 * @param abilityList
	 * @param tagList
	 * @return
	 */
	public boolean saveOrUpdateTranslator(TblTranslator translator, List<TblTranslatorAbility> abilityList, List<TblTranslatorTags> tagList) {
		if (null == translator) {
			throw new RuntimeException("译员不存在");
		}
		if (null == abilityList || abilityList.isEmpty()) {
			TblTranslatorAbility condition = new TblTranslatorAbility();
			condition.setTranslatorId(translator.getId());
			abilityList = translatorAbilityMapper.select(condition);
			if (null == abilityList || abilityList.isEmpty()) {
				throw new RuntimeException("译员能力为null");
			}
		}
		if (null == tagList || tagList.isEmpty()) {
			TblTranslatorTags condition = new TblTranslatorTags();
			condition.setTranslatorId(translator.getId());
			tagList = translatorTagsMapper.select(condition);
		}
		String coreserverHostUrl = (String) PropertyPlaceholderConfigurerExt.getContextProperty("coreserver.root.url");
		String trserverBaseKey = (String) PropertyPlaceholderConfigurerExt.getContextProperty("trserver.base.key");
		String url = coreserverHostUrl + CoreServerContants.SAVE_OR_UPDATE_TRANSLATOR_REDIS;
		SaveOrUpdateTranslatorParam req = new SaveOrUpdateTranslatorParam();
		req.setSignId(translator.getId());
		req.setAppKey(trserverBaseKey);
		req.setAreaCode(translator.getCountryCode());
		req.setPhone(translator.getPhone());
		req.setTranslatorNature(translator.getTranslatorType().toString());
		req.setTranslatorName(translator.getNickName());
		req.setTranslatorIcon(translator.getImage());
		req.setMotherTongue(String.valueOf(translator.getSrcLangId()));
		req.setToken(getToken());
		req.setTranslatorAbility(converToKeyValue(abilityList));
		req.setTranslatorTag(converToTagStr(tagList));
		String result = HttpRequestFactory.getHttpRequest(HttpRequestMethod.POST).send(url, req);
		JSONObject json = JSON.parseObject(result);
		if (null != json && json.containsKey("data") && json.getString("data").equals(translator.getId())) {
			return true;
		}
		return false;
	}

	private String converToTagStr(List<TblTranslatorTags> tagList) {
		// 去除标签属性为OTHER的标签(CoreServer不接受OTHER标签)
		if (null == tagList || tagList.size() == 0) {
			return "";
		}
		StringBuilder translatorTags = new StringBuilder("");
		for (TblTranslatorTags tag : tagList) {
			if (!"OTHER".equals(tag.getTranslatorTag())) {
				translatorTags.append(tag.getTranslatorTag()).append(",");
			}
		}

		if (translatorTags.length() == 0) {
			return "";
		}
		return translatorTags.substring(0, translatorTags.length() - 1);
	}

	/**
	 * 将译员语言能力转为字符串，形式为: {1: 1, 2: 1}, key为语言ID，value为等级，最大为100
	 * 
	 * @param abilityList
	 * @return
	 */
	private static String converToKeyValue(List<TblTranslatorAbility> abilityList) {
		Map<String, String> abilityMap = new HashMap<String, String>();
		for (TblTranslatorAbility ability : abilityList) {
			abilityMap.put(String.valueOf(ability.getAbilityId()), ability.getAbilityLevel());
		}
		return JSONObject.toJSONString(abilityMap);
	}

	/**
	 * 将所有正常状态的译员刷到CoreServer的Redis缓存中
	 * 
	 * @return
	 */
	public boolean pushTranslatorToCoreServer() {
		boolean flag = false;
		List<TblTranslator> list = translatorMapper.selectAll();
		try {
			for (TblTranslator temp : list) {
				if (null != temp && "InUse".equals(temp.getDataStatus())) {
					flag = saveOrUpdateTranslator(temp, null, null);
					if (!flag) {
						break;
					}
				}
			}
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}
}
